<html>
	<head>
		<script type="text/javascript">
			function editDiagram(image)
			{
				var initial = image.getAttribute('src');
				image.setAttribute('src', 'http://www.draw.io/images/ajax-loader.gif');
				var iframe = document.createElement('iframe');
				iframe.setAttribute('frameborder', '0');
				
				var close = function()
				{
					image.setAttribute('src', initial);
					document.body.removeChild(iframe);
					window.removeEventListener('message', receive);
				};

				var receive = function(evt)
				{
					if (evt.data.length > 0)
					{
						var msg = JSON.parse(evt.data);
			
						if (msg.event == 'init')
						{
							iframe.contentWindow.postMessage(JSON.stringify({action: 'load',
								xmlpng: initial}), '*');
						}
						else if (msg.event == 'export')
						{
							close();
							image.setAttribute('src', msg.data);
							save(location.href);
						}
						else if (msg.event == 'save')
						{
							iframe.contentWindow.postMessage(JSON.stringify({action: 'export',
								format: 'xmlpng', spin: 'Updating page'}), '*');
						}
						else if (msg.event == 'exit')
						{
							close();
						}
					}
				};

				window.addEventListener('message', receive);
				iframe.setAttribute('src', 'https://www.draw.io/?embed=1&ui=atlas&spin=1&modified=unsavedChanges&proto=json');
				document.body.appendChild(iframe);
			};
			
			function save(url)
			{
				if (url != null)
				{
					var req = new XMLHttpRequest();
					req.withCredentials = true;
					var wnd = (url != window.location.href) ? window.open() : null;
			
					req.onreadystatechange = function()
					{
						if (req.readyState == 4)
						{
							if (req.status != 200 && req.status != 201)
							{
								if (wnd != null)
								{
									wnd.close();
								}
								
								alert('Error ' + req.status);
							}
							else if (wnd != null)
							{
								wnd.location.href = url;
							}
						}
					};
				
					req.open('PUT', url, true);
					req.send(document.documentElement.outerHTML);
				}
			}
		</script>
		<style type="text/css">
			html, body, #wrapper {
				height:100%;
				width:100%;
				margin:0;
				padding:0;
				border:0;
			}
			#wrapper td {
				vertical-align:middle;
				text-align:center;
			}
			iframe {
				border:0;
				position:fixed;
				top:0;
				left:0;
				right:0;
				bottom:0;
				width:100%;
				height:100%
			}
		</style>
	</head>
<body>
<table id="wrapper">
	<tr>
		<td><img id="image" style="max-width:100%;cursor:pointer;" onclick="editDiagram(this);" src="" /></td>
	</tr>
</table>
</body>
</html>
